class CodeController {

    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        redirect(action:create)
        if(!params.max) params.max = 10
        [ codeList: Code.list( params ) ]
    }

    def show = {
        def code = Code.get( params.id )

        if(!code) {
            flash.message = "Code not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ code : code ] }
    }

    def delete = {
        redirect(action:create)
        def code = Code.get( params.id )
        if(code) {
            code.delete()
            flash.message = "Code ${params.id} deleted"
            redirect(action:create)
        }
        else {
            flash.message = "Code not found with id ${params.id}"
            redirect(action:create)
        }
    }

    def edit = {
        def code = Code.get( params.id )

        if(!code) {
            flash.message = "Code not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ code : code ]
        }
    }

    def update = {
        def code = Code.get( params.id )
        if(code) {
            code.properties = params
            if(!code.hasErrors() && code.save()) {
                flash.message = "Code ${params.id} updated"
                redirect(action:show,id:code.id)
            }
            else {
                render(view:'edit',model:[code:code])
            }
        }
        else {
            flash.message = "Code not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def code = new Code()
        code.properties = params
        return ['code':code]
    }

    def save = {
        def code = new Code(params)
        if(!code.hasErrors() && code.save()) {
            flash.message = "Code ${code.id} created"
            redirect(action:show,id:code.id)
        }
        else {
            render(view:'create',model:[code:code])
        }
    }
    
}
